package cn.zh.order.service.impl;

import cn.zh.order.domain.vo.OrderVo;
import cn.zh.order.feign.AccountFeignService;
import cn.zh.order.feign.StorageFeignService;
import cn.zh.order.service.OrderService;
import cn.zh.order.service.OrderServiceSeataTcc;
import io.seata.core.context.RootContext;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


/**
 * @author zh
 */
@Service
@Slf4j
public class OrderServiceImpl implements OrderService {

    @Autowired
    private AccountFeignService accountFeignService;
    
    @Autowired
    private StorageFeignService storageFeignService;

    @Autowired
    private OrderServiceSeataTcc orderServiceSeataTcc;
    
    @Override
    @GlobalTransactional(name="createOrder",rollbackFor=Exception.class)
    public void saveOrder(OrderVo orderVo, Boolean hasException) {
        log.info("=============用户下单=================");
        log.info("当前 XID: {}", RootContext.getXID());
        
        // 保存订单

        Integer orderId = orderServiceSeataTcc.prepareSaveOrder(orderVo);

        // 扣减库存
        storageFeignService.deduct(orderVo.getCommodityCode(), orderVo.getCount());
        
        // 扣减余额
        Boolean debit= accountFeignService.debit(orderVo.getUserId(), orderVo.getMoney());

//        if(!debit){
//            // 解决 feign整合sentinel降级导致Seata失效的处理
//            throw new RuntimeException("账户服务异常降级了");
//        }

        if (hasException){
            throw new RuntimeException("-------------内部服务异常------------");
        }
        
    }
}
